//
//  HYCRecommendController.m
//  FamilyTravel
//
//  Created by dllo on 15/10/21.
//  Copyright (c) 2015年 蓝鸥科技. All rights reserved.
//

#import "HYCRecommendController.h"
#import "HYCMemoryTool.h"
#import "HYCHeadDocument.h"
#pragma mark 首页推荐

#define WIDTH self.view.frame.size.width
#define HEIGHT self.view.frame.size.height
#define SWIDTH [UIScreen mainScreen].bounds.size.width
#define SHEIGHT [UIScreen mainScreen].bounds.size.height

@interface HYCRecommendController ()<UITableViewDelegate, UITableViewDataSource, UISearchBarDelegate, UIScrollViewDelegate, UITextFieldDelegate>
@property(nonatomic, retain) UITableView *tableView;
@property(nonatomic, retain) NSMutableArray *arr;
@property(nonatomic, retain) NSMutableArray *scrArr;
@property(nonatomic, retain) NSMutableArray *lowArr;
@property(nonatomic, retain) MBProgressHUD *hud;
@property(nonatomic, retain) UIScrollView *scrollView;
@property(nonatomic, assign) NSInteger page;
@property(nonatomic, assign) NSInteger secPage;
@property(nonatomic, retain) UIImageView *image;


@property(nonatomic, retain) NSDictionary *dic;

@end

@implementation HYCRecommendController
- (void)dealloc {
    [_hud release];
    [_arr release];
    [_scrArr release];
    [_tableView release];
    [_scrollView release];
    [_image release];
    [_dic release];
    
    [super dealloc];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    self.lowArr = [NSMutableArray array];
    self.page = 1;
    self.title = @"值得去的地方";
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SWIDTH, SHEIGHT - 70) style:UITableViewStyleGrouped];
    [self.view addSubview:self.tableView];
    [_tableView release];
    self.tableView.delegate = self;
    self.tableView.dataSource =self;
    
    //横岗去掉
    self.tableView.separatorStyle = NO;
    
    self.scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, SWIDTH, (SHEIGHT) / 3)];
    
    self.tableView.tableHeaderView = self.scrollView;
    
    // 边界回弹
    self.scrollView.bounces = NO;
    self.scrollView.pagingEnabled = YES;
    self.scrollView.delegate = self;
    self.scrollView.contentOffset = CGPointMake(WIDTH, 0);
    self.scrollView.showsHorizontalScrollIndicator = YES;
    [_scrollView release];
    
    [NSTimer scheduledTimerWithTimeInterval:3 target:self selector:@selector(changeAction) userInfo:nil repeats:YES];
    
    self.hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    self.hud.labelText = @"加载中...";
    
    UIImage *beanTripBackgroundImage=[UIImage imageNamed:@"tou.jpg"];
    [self.navigationController.navigationBar setBackgroundImage:beanTripBackgroundImage forBarMetrics:UIBarMetricsDefault];
    
    [self netWorkingJudge];
}

- (void)netWorkingJudge {
    AFNetworkReachabilityManager *judgeManager = [AFNetworkReachabilityManager sharedManager];
    
    [judgeManager startMonitoring];
    [judgeManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        
        if (status == 1 || status == 2) {
            [self secondCreateData];
            [self createData];
            // 上拉刷新下拉加载
            self.tableView.header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(HeaderAction)];
            
            self.tableView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
                // 进入刷新状态后会自动调用这个block
                self.page++;
                [self secondCreateData];
                
            }];
        } else {
            NSDictionary *dic = [HYCMemoryTool backToDictionary:@"hyc.plist"];
            if (dic == nil) {
                UIAlertView *alert = [[UIAlertView alloc]initWithTitle:nil message:@"没有网络" delegate:self cancelButtonTitle:@"取消" otherButtonTitles: nil];
                [alert show];
                [alert release];
            } else {
                
                [HYCMemoryTool saveInPlist:dic Plist:@"hyc.plist"];
                self.arr = [NSMutableArray array];
                for (NSDictionary *tempDic in dic[@"data"][@"discount"]) {
                    HYCRecommendMovie *movie = [[HYCRecommendMovie alloc] init];
                    [movie setValuesForKeysWithDictionary:tempDic];
                    [self.arr addObject:movie];
                    [movie release];
                }
                // 轮播图
                self.scrArr = [NSMutableArray array];
                for (NSDictionary *tempDic in dic[@"data"][@"slide"]) {
                    HYCRecommendMovie *movie = [[HYCRecommendMovie alloc] init];
                    [movie setValuesForKeysWithDictionary:tempDic];
                    [self.scrArr addObject:movie];
                    [movie release];
                }
                [self rotaImage];
                [self.tableView reloadData];
                
                NSDictionary *oneDic = [HYCMemoryTool backToDictionary:@"one.plist"];
                [HYCMemoryTool saveInPlist:oneDic Plist:@"one.plist"];
                //        NSLog(@"%@", self.arr);
                // 轮播图
                for (NSDictionary *tempDic in oneDic[@"data"]) {
                    HYCSecondRecommendModel *movie = [[HYCSecondRecommendModel alloc] init];
                    [movie setValuesForKeysWithDictionary:tempDic];
                    [self.lowArr addObject:movie];
                }
                 [self.hud removeFromSuperview];
                [self.tableView reloadData];
                
            }
        }
    }];
}
// 刷新
-(void)HeaderAction{
    
    [self.lowArr removeAllObjects];
    [self.arr removeAllObjects];
    [self createData];
    [self secondCreateData];
    
}

// 当前分区个数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}
// 给分区设定标题
- (NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
    if (section == 0) {
        return @"特价折扣";
    }
    return @"特价折扣";
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    // 自定义分区标题
    if (section == 0) {
        UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(5, 0, WIDTH - 10, 50)];
        
        UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
        button.frame = CGRectMake(WIDTH / 2 - 50, 4, 100, 20);
        button.font = [UIFont systemFontOfSize:18];
        [button setTitle:@"更多折扣" forState:UIControlStateNormal];
        [footerView addSubview:button];
        [button addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
        return footerView;
    }else {
        UIView *View = [[UIView alloc] initWithFrame:CGRectMake(5, 0, WIDTH - 10, 1)];
        UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
        button.frame = CGRectMake(20, 0, 200, 10);
        [View addSubview:button];
        return View;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 15;
}
// Button的点击方法
- (void)buttonAction:(UIButton *)button {
    HYCPushDiscountViewController *pDVC = [[HYCPushDiscountViewController alloc] init];
    
    pDVC.hidesBottomBarWhenPushed = YES;
    
    [self.navigationController pushViewController:pDVC animated:YES];
    
    pDVC.title = @"全部城市";
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        return HEIGHT / 2.994;
    }else {
        return HEIGHT / 3.6;
    }
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return self.arr.count;
    }else {
        return self.lowArr.count;
    }
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    // 点击方法;
    HYCPushRecommendViewController *pRVC = [[HYCPushRecommendViewController alloc] init];
    pRVC.hidesBottomBarWhenPushed = YES;
    if (self.arr.count != 0 && self.lowArr.count != 0) {
        if (indexPath.section == 0) {
            NSString *str = [NSString stringWithFormat:@"http://m.qyer.com/z/deal/%@/?source=app&client_id=qyer_android&track_app_version=6.2&track_deviceid=866818029530472&track_user_id=6904760", [self.arr[indexPath.row] number]];
            pRVC.str = str;
            [self.navigationController pushViewController:pRVC animated:YES];
            pRVC.title = @"折扣详情";
        }else {
            pRVC.str = [self.lowArr[indexPath.row] view_url];
            [self.navigationController pushViewController:pRVC animated:YES];
            pRVC.title = @" ";
        }
    }
}
// 解析
- (void)secondCreateData {
    NSString *urlOne = [NSString stringWithFormat:@"http://open.qyer.com/qyer/recommands/trip?client_id=qyer_ios&client_secret=cd254439208ab658ddf9&count=10&page=%ld", (long)self.page];
    NSString *urlStr = [NSString stringWithFormat:@"%@%@", urlOne, @"&track_app_channel=App%2520Store&track_app_version=6.7&track_device_info=iPhone%25204%28ChinaMobile%2CChinaUnicom%29&track_deviceid=AB5B28ED-8670-4190-873A-F09EFE3EB3E8&track_os=ios%25207.1.2&type=index&v=1"];
    NSURL *url = [NSURL URLWithString:urlStr];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        NSMutableDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
        [HYCMemoryTool saveInPlist:dic Plist:@"one.plist"];
        for (NSDictionary *tempDic in dic[@"data"]) {
            HYCSecondRecommendModel *movie = [[HYCSecondRecommendModel alloc] init];
            [movie setValuesForKeysWithDictionary:tempDic];
            [self.lowArr addObject:movie];
        }
        [self.hud removeFromSuperview];
        [self.tableView reloadData];
        [self.tableView.header endRefreshing];
        [self.tableView.footer endRefreshing];
    }];
}
- (void)createData {
    NSString *strURL = @"http://open.qyer.com/qyer/recommands/entry?client_id=qyer_ios&client_secret=cd254439208ab658ddf9&count=20&page=1&track_app_channel=App%2520Store&track_app_version=6.7&track_device_info=iPhone%25204%28ChinaMobile%2CChinaUnicom%29&track_deviceid=AB5B28ED-8670-4190-873A-F09EFE3EB3E8&track_os=ios%25207.1.2&v=1";
    NSURL *url = [NSURL URLWithString:strURL];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    // 判断
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        NSMutableDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
        [HYCMemoryTool saveInPlist:dic Plist:@"hyc.plist"];
        self.arr = [NSMutableArray array];
        for (NSDictionary *tempDic in dic[@"data"][@"discount"]) {
            HYCRecommendMovie *movie = [[HYCRecommendMovie alloc] init];
            [movie setValuesForKeysWithDictionary:tempDic];
            [self.arr addObject:movie];
            [movie release];
        }
        // 轮播图
        self.scrArr = [NSMutableArray array];
        for (NSDictionary *tempDic in dic[@"data"][@"slide"]) {
            HYCRecommendMovie *movie = [[HYCRecommendMovie alloc] init];
            [movie setValuesForKeysWithDictionary:tempDic];
            [self.scrArr addObject:movie];
            [movie release];
        }
        [self rotaImage];
    }];
}
#pragma  mark 轮播图
- (void)rotaImage {
    UIImageView *firstImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, SWIDTH, (SHEIGHT + 64) / 3)];
    [firstImageView sd_setImageWithURL:[NSURL URLWithString:[self.scrArr[self.scrArr.count - 1] photo]]];
    [self.scrollView addSubview:firstImageView];
    firstImageView.userInteractionEnabled = YES;
    firstImageView.tag = 1000 + self.scrArr.count - 1;
    [firstImageView release];
    for (NSInteger i = 0; i < self.scrArr.count; i++) {
        UIImageView *scrImageView = [[UIImageView alloc] initWithFrame:CGRectMake(SWIDTH * i, 0, SWIDTH, (SHEIGHT + 64) / 3)];
        [scrImageView sd_setImageWithURL:[NSURL URLWithString:[self.scrArr[i] photo]]];
        [self.scrollView addSubview:scrImageView];
        scrImageView.userInteractionEnabled = YES;
        scrImageView.tag = 1000 + i;
        [scrImageView release];
        // 轮播图点击事件
        UITapGestureRecognizer *single = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(fingerIncident:) ];
        //手指数
        single.numberOfTouchesRequired = 1;
        //点击次数
        single.numberOfTapsRequired = 1;
        // 增加事件响应者
        [scrImageView addGestureRecognizer:single];
    }
    UIImageView *lastImageView = [[UIImageView alloc] initWithFrame:CGRectMake(SWIDTH * self.scrArr.count, 0, SWIDTH, (SHEIGHT + 64) / 3)];
    [lastImageView sd_setImageWithURL:[NSURL URLWithString:[self.scrArr[0] photo]]];
    lastImageView.userInteractionEnabled = YES;
    [self.scrollView addSubview:lastImageView];
    lastImageView.tag = 1000;
    [lastImageView release];
    lastImageView.userInteractionEnabled = YES;
    [self.hud removeFromSuperview];
    [self.tableView reloadData];
    self.scrollView.contentSize = CGSizeMake(WIDTH * (self.scrArr.count + 2), 0);
}
// 轮播图点击方法
- (void)fingerIncident:(UITapGestureRecognizer *)single {
    HYCPushRecommendViewController *pRVC = [[HYCPushRecommendViewController alloc] init];
    pRVC.str = [self.scrArr[single.view.tag - 1000] urlStr];
    pRVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:pRVC animated:YES];
}
//轮播图
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    if (self.scrollView.contentOffset.x ==( self.scrArr.count + 1) * WIDTH) {
        self.scrollView.contentOffset = CGPointMake(0, 0);
    }else if (self.scrollView.contentOffset.x == 0) {
        self.scrollView.contentOffset = CGPointMake(self.scrArr.count * SWIDTH, 0);
    }
}
- (void)changeAction{
    [self.scrollView setContentOffset:CGPointMake(self.scrollView.contentOffset.x + SWIDTH, 0) animated:YES];
    // 判断是否到当前的最后一张, 如果到了, 需要把偏移量设置到第一张图片的位置
    if (self.scrollView.contentOffset.x == self.scrArr.count * SWIDTH) {
        self.scrollView.contentOffset = CGPointMake(0, 0);
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        static NSString *reuse = @"reuse";
        HYCRecommendCell *cell = [tableView dequeueReusableCellWithIdentifier:reuse];
        if (!cell) {
            cell = [[[HYCRecommendCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:reuse] autorelease];
        }
        if (self.arr.count != 0) {
            HYCRecommendMovie *model = _arr[indexPath.row];
            cell.model = model;
            // cell动画
            cell.layer.shadowColor = [[UIColor blackColor]CGColor];
            cell.alpha = 0;
            [UIView beginAnimations:@"rotation" context:NULL];
            [UIView setAnimationDuration:1];
            cell.alpha = 1;
            [UIView commitAnimations];
        }
        return cell;
    } else {
        static NSString *reuse= @"reuseSencond";
        HYCSecondRecommendCell *cell = [tableView dequeueReusableCellWithIdentifier:reuse];
        if (!cell) {
            cell = [[[HYCSecondRecommendCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:reuse] autorelease];
        }
        if (self.lowArr.count != 0) {
            HYCSecondRecommendModel *model = self.lowArr[indexPath.row];
            cell.model = model;
            // cell动画
            cell.layer.shadowColor = [[UIColor blackColor]CGColor];
            cell.alpha = 0;
            [UIView beginAnimations:@"rotation" context:NULL];
            [UIView setAnimationDuration:1];
            cell.alpha = 1;
            [UIView commitAnimations];
        }
        return cell;
    }
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
@end
